package token

import "bytes"

type TagValue []byte

func (t TagValue) String() string {
	return string(t)
}

func (t TagValue) Value() AttributeValue {
	return AttributeValue(t)
}

func (t TagValue) Values() []AttributeValue {
	attrs := make([]AttributeValue, 0, 1)
	quoted := false
	consumed := 0
	for i, c := range t {
		if c == '"' {
			quoted = !quoted
		} else if (c == ',' && !quoted) || i == len(t)-1 {
			var raw []byte
			if c == ',' {
				raw = t[consumed:i]
				consumed = i + 1
			} else {
				raw = t[consumed : i+1]
				// 结束了, 无需consumed
			}
			attrs = append(attrs, raw)
		}
	}
	return attrs
}

func (t TagValue) Attributes() Attributes {
	attrs := make(Attributes)
	quoted := false
	consumed := 0
	for i, c := range t {
		if c == '"' {
			quoted = !quoted
		}
		if (c == ',' && !quoted) || i == len(t)-1 {
			var raw []byte
			if c == ',' {
				raw = t[consumed:i]
				consumed = i + 1
			} else {
				raw = t[consumed : i+1]
				// 结束了, 无需consumed
			}
			key, value, ok := bytes.Cut(raw, []byte("="))
			if !ok {
				continue
			}
			attrs[string(key)] = value
		}
	}
	return attrs
}

func NewTagValueValue(attr AttributeValue) TagValue {
	return TagValue(attr)
}

func NewTagValueValues(attrs ...AttributeValue) TagValue {
	var m int
	for _, attr := range attrs {
		m += len(attr)
	}
	if m == 0 {
		return nil
	}
	m += len(attrs) // 逗号的数量
	buf := &bytes.Buffer{}
	buf.Grow(m)
	for _, attr := range attrs {
		buf.Write(attr)
		buf.WriteByte(',')
	}
	return buf.Bytes()
}

func NewTagValueAttributes(attrs Attributes) TagValue {
	var m int
	for key, value := range attrs {
		m += len(key) + len(value)
	}
	if m == 0 {
		return nil
	}
	m += len(attrs) * 2 // 逗号和等号的数量
	buf := &bytes.Buffer{}
	buf.Grow(m)
	for key, value := range attrs {
		buf.WriteString(key)
		buf.WriteByte('=')
		buf.Write(value)
		buf.WriteByte(',')
	}
	return buf.Bytes()[:buf.Len()-1]
}
